package com.zoe.wan.android.example.fragment.home

import android.app.Application
import android.app.SharedElementCallback
import androidx.lifecycle.viewModelScope
import com.zoe.wan.android.example.repositry.Repository
import com.zoe.wan.android.example.repositry.data.home.HomeBannerData
import com.zoe.wan.android.example.repositry.data.home.HomeBannerDataItem
import com.zoe.wan.android.example.repositry.data.home.HomeListDataData
import com.zoe.wan.base.BaseViewModel
import com.zoe.wan.base.SingleLiveEvent
import kotlinx.coroutines.launch

class FragHomeViewModel(application: Application) : BaseViewModel(application) {

    val list = SingleLiveEvent<List<HomeListDataData>?>()

    val bannerItem = SingleLiveEvent<HomeBannerData?>()

    var pageCount: Int = 0

    init {
        initData(){}
    }

    fun initData(loadMore:Boolean = false,callback: () -> Unit) {
        if (loadMore){
            pageCount++
        }else{
            getBanner()
            pageCount = 0
        }
        getHomeList(loadMore){
            callback.invoke()
        }

    }

    private fun getHomeList(loadMore:Boolean,callback: () -> Unit) {
        viewModelScope.launch {
            val data = Repository.getHomeList("${pageCount}")
            if (data != null) {
                if (loadMore){
                    val newList = (list.value ?: emptyList()) + (data?.datas ?: emptyList())
                    list.postValue(newList)
                }else{
                    list.postValue(data.datas)
                }
            }else{
                if (loadMore && pageCount > 0){
                    pageCount--
                }
            }
            callback.invoke()
        }
    }

    private fun getBanner() {
        viewModelScope.launch {
            val data = Repository.getBannerList()
            if (data != null) {
                bannerItem.postValue(data)
            }
        }
    }

    fun collect(id: String, callback: () -> Unit) {
        viewModelScope.launch {
            val data = Repository.collect(id)
            callback.invoke()
        }
    }
}